import { thin } from "../thin3.mjs";
import { confirm } from "./dialog.mjs";

export function datalist_template(container, template) {
  datalist({ ...template.datalist, ...{ container: container } });
}

export function datalist({
  id,
  container,
  gridview_class,
  gridview_height,
  gridview_rowclass,
  title,
  listapi,
  listquery,
  listcols,
  groupdatapath,
  grouprowtemplate,
  listdatapath,
  rowclick,
  rowedit = false,
  rowselect,
  rowdrag,
  rowinsert,
  rowdelete,
  rowchange,
  summarydatapath,
  itemapi,
  itemquery,
  linkfields = [],
  itemviewonopen,
  itemviewtitle = " ",
  itemviewwidth,
  itemviewheight,
  itemtemplate,
  // onitemviewclose,
  updateapi,
  insertapi,
  deleteapi,
}) {
  let _data, cols;

  if (rowselect) {
    listcols.unshift({
      col: {
        input: "",
        type: "checkbox",
        class: "rowselect",
        event: {
          change: (e) => {
            selecthandler();
          },
        },
      },
      filter: {
        input: "",
        type: "checkbox",
        class: "selectall",
        event: {
          change: (e) => {
            // console.log(e);
            thin("input.rowselect", container).each((node) => {
              node.checked = e.sender.checked;
            });
            selecthandler();
          },
        },
      },
      title: "",
      class: "fixed",
    });
  }

  function selecthandler() {
    // console.log({selecthandler})
    if (typeof rowselect === "function") {
      let selected = [];
      thin("input.rowselect", container).each((node) => {
        if (node.checked) selected.push(node.closest("tr").thin_data);
      });
      // console.log(selected);
      rowselect(selected);
    }
  }

  if (rowdrag) {
    // listcols.push({
    //   col: {
    //     span: "=",
    //     click: (e) => {
    //       console.log(e);
    //       let tr = e.sender.closest("tr");
    //       tr.setAttribute("draggable", true);
    //     },
    //   },
    //   readonly: true,
    //   class: "fixright",
    // });
  }

  thin(container).render([
    // thin_render(container, [
    { h2: title, when: title },
    {
      button: "add",
      click: (e) => {
        console.log(e);
        itemviewer({
          // listquery,
          mode: "insert",
          onclose: () => {
            e.done();
          },
        });
      },
      when: insertapi && !rowinsert,
    },
    {
      ajax: listapi,
      query: listquery,
      loading: "loading....",
      success: [
        {
          gridview: listcols,
          id: id,
          class: gridview_class,
          height: gridview_height,
          groupdatapath: groupdatapath,
          grouprowtemplate: grouprowtemplate,
          datapath: listdatapath,
          summarydatapath: summarydatapath,
          rowclass: gridview_rowclass,
          rowedit: rowedit,
          rowdrag: rowdrag,
          rowinsert: rowinsert && insertapi ? insert_row : false,
          rowdelete: rowdelete && deleteapi ? delete_row : false,
          rowchange: (e) => {
            // console.log(e);
            if (updateapi) {
              // console.log({ update: { ...e.org_data, ...e.new_data } });
              thin
                .ajax({
                  url: updateapi,
                  data: { ...listquery, ...e.org_data, ...e.new_data },
                })
                .done((d) => {
                  // console.log({ updated: d });
                });
            } else if (rowchange) {
              rowchange(e);
            }
          },
          rowclick:
            rowclick || itemtemplate
              ? (e) => {
                  console.log(e);
                  if (rowclick) rowclick(e);
                  else if (itemtemplate) {
                    if (onclose)
                      e.onclose = function () {
                        onclose();
                      };
                    if (itemapi) {
                      let query = itemquery || {};

                      if (linkfields) {
                        linkfields.forEach((key) => {
                          if (e.org_data.hasOwnProperty(key)) {
                            query[key] = e.org_data[key];
                          }
                        });
                      }
                      itemviewer({ data: e.org_data, query, mode: "read" });
                    } else {
                      itemviewer({ data: e.org_data, mode: "read" });
                    }
                  }
                }
              : undefined,
        },
        {
          if: ({ container, data, param }) => {
            // console.log({ p });
            return data.totalrecord && data.pagesize;
          },
          then: {
            pager: true,
          },
        },
      ],
    },
  ]);

  function delete_row(p) {
    console.log(p);
    let data = { ...listquery, ...p.org_data };
    console.log({ data });
    confirm("是否删除数据？")
      .confirmed((d) => {
        console.log({ confirmed: d });
        thin.ajax({
          url: deleteapi,
          data: data,
          success: () => {
            p.done();
            p.rerender();
          },
        });
      })
      .cancelled(() => {
        p.done();
      });
  }

  function insert_row(p) {
    console.log(p);
    let data = { ...listquery, ...p.org_data, ...p.new_data };
    console.log(data);
    thin.ajax({
      url: insertapi,
      data: data,
      success: () => {
        p.done();
        p.rerender();
      },
    });
  }

  function itemviewer({ query, data, mode, onclose }) {
    console.log({ query });
    if (itemviewonopen) itemviewonopen({ query, data, mode });

    thin.pop({
      header: itemviewtitle,
      render: render,
      width: itemviewwidth || 960,
      height: itemviewheight || 700,
      onclose: () => {
        thin("ajax", container).rerender();
        if (onclose) onclose();
      },
      data: data || query,
    });

    function render({ container, _data }) {
      console.log({ container, _data });
      if (data) {
        render_with_data(data);
      } else if (query) {
        thin.ajax({
          url: itemapi,
          data: query,
          success: (data) => {
            // prepareitemtemplate();
            render_with_data(data);
          },
        });
      } else {
        render_with_data({});
      }

      function render_with_data(data) {
        if (itemtemplate) {
          thin(container).render({
            formview: itemtemplate,
            data,
            mode,
            oninsert: insertapi ? update : undefined,
            onsave: updateapi ? update : undefined,
            ondelete: deleteapi ? deletehandler : undefined,
          });
        }
        function update(e) {
          let data = {
            ...(itemquery || listquery),
            ...query,
            ...e.org_data,
          };
          console.log({ data, itemquery, listquery });
          thin
            .ajax({
              url: mode === "insert" ? insertapi || updateapi : updateapi,
              data,
              // success: (data) => {
              //   e.readmode();
              // },
            })
            .done((data) => {
              e.readmode();
            })
            .fail((err) => {
              console.log(err);
              alert(err.statusText.concat("\n\r", err.responseText));
            });
        }
        function deletehandler(e) {
          console.log(e);
          let data = { ...itemquery, ...listquery, ...query, ...e.org_data };
          // Object.assign(data, e.org_data);
          // Object.assign(data, query);
          // Object.assign(data, itemquery);
          console.log({ data, listquery, itemquery });
          thin.ajax({
            url: deleteapi,
            data,
            success: (data) => {
              // e.readmode();
              thin.popclose(e.sender);
            },
          });
        }
      }
    }
  }
}
